package com.jlyx.scwechatgoods.service.accesstoken.impl;

import com.alibaba.fastjson.JSONObject;
import com.jlyx.scwechatgoods.common.RestTemplateHelper;
import com.jlyx.scwechatgoods.service.accesstoken.AccessTokenService;
import com.jlyx.scwechatgoods.utils.WeChatGoodsApiUrl;
import com.jlyx.scwechatgoods.wechatenum.WeChatEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author sesshomaru
 * @date 2019/12/3 17:34
 */
@Service
@Slf4j
public class AccessTokenServiceImpl implements AccessTokenService {

    @Value("${jlyx.wechat.appid}")
    private String appid;
    @Value("${jlyx.wechat.appsecret}")
    private String appsecret;

    @Autowired
    private RestTemplateHelper restTemplateHelper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public String getAccessToken() {
     /*   String accessToken = (String)redisTemplate.opsForValue().get(WeChatEnum.access_token.getValue());
        if(StringUtils.isNotBlank(accessToken)){
            return accessToken;
        }*/
        String requestUrl = String.format(WeChatGoodsApiUrl.WX_GET_ACCESS_TOKEN_URL,appid,appsecret);
        String response = restTemplateHelper.get(requestUrl);
        log.info("获取access_token响应报文:{}",response);
        JSONObject accessTokenResponse = JSONObject.parseObject(response);
        String accessToken = accessTokenResponse.getString(WeChatEnum.access_token.getValue());
       // redisTemplate.opsForValue().set("access_token",accessToken,1, TimeUnit.MINUTES);
        return accessToken;
    }

    @Override
    public boolean refreshAccessToken() {
        return true;
    }
}
